<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="/static/js/layui/css/layui.css" >
    <link rel="stylesheet" href="/static/code/css/chat_mini.css">
</head>

<body>
    <div class="chat-container" id="app">
        <div class="layui-row chat-header">
            <div class="layui-col-xs2 chat-header-avatar">
                <img src="{$shop['avatar']}" onerror="nopic()" class="agent-avatar" />
            </div>
            <div class="layui-col-xs7 chat-header-title">
                为您服务
            </div>
            <div class="layui-col-xs3 chat-header-tool" id="closeBtn">
                <i class="layui-icon layui-icon-down"></i>
            </div>
        </div>
        <div class="layui-row chat-body">
            <div class="chat-box">
                <div class="wrap_ad"
                     style="margin: 0 auto 16px;border: 1px solid #DDE5ED; padding: 5px;font-size: 12px;text-align: center;word-wrap: break-word;overflow: hidden;display: none;">
                    <a target="_blank" href="javascript:void(0);">
                        <img style="max-width: 100%;" src="">
                    </a>
                </div>
            </div>
        </div>
        <div class="layui-row chat-footer">
            <div class="text-holder">
                <textarea id="textarea" placeholder="请反馈您的问题，我们会尽快回复~~"></textarea>
            </div>
            <div class="send-bar">
                <div class="tool-box">
                    <i class="layui-icon layui-icon-face-smile" id="face" style="display: none;"></i>
                    <i class="layui-icon layui-icon-picture" id="image" style="display: none;"></i>
                    <span class="server_status">服务连接状态：<span class="layui-badge layui-bg-green">已连接</span></span>
                </div>
                <div class="send-btn-div">
                    <input type="button" value="发送" class="send-input" id="sendBtn" style="float: right;">
                </div>
            </div>
        </div>
        <div class="layui-row copyright">
            <div class="layui-col-md12 layui-col-xs12">
                <a href="{$version.url}" target="_blank">{$shop['name']}-{$version.name} 提供软件支持</a>
            </div>
        </div>
    </div>

    <div class="wrap_hide" style="display: none;">
        <div class="clearfloat guest_wrap">
            <div class="author-name">
                <small class="chat-date">xxx</small>
            </div>
            <div class="right">
                <div class="chat-message">xxx</div>
                <div class="chat-avatars">
                    <img src="">
                </div>
            </div>
        </div>
        <div class="clearfloat kf_wrap">
            <div class="author-name">
                <small class="chat-date">xxx</small>
            </div>
            <div class="left">
                <div class="chat-avatars">
                    <img src=""></div>
                <div class="chat-message">xxx</div>
            </div>
        </div>
        <div class="clearfloat system_wrap">
            <div class="author-name">
                <small class="chat-system">xxx</small>
            </div>
        </div>
        <div style="clear:both" class="chat-sep"></div>
    </div>

    <script src="/static/js/jquery.2.1.4.min.js"></script>
    <script src="/static/common/js/websocket.min.js"></script>
    <script src="/static/js/layui/layui.js"></script>

    <script>
        window.nopic=function(){
            var img=event.srcElement;
            img.src='/static/common/image/null.png';
            img.onerror=null;// 控制不要一直跳动
        }
        var uid = Math.floor(Math.random() * (5000 - 1000)) + 1000;
        var shop_id = {$shop['id']};
        const options = {
            url: '{$socket}',
            pingTimeout: 30000,
            pongTimeout: 30000,
            reconnectTimeout: 10000,
            pingMsg: "ping",
            data: {
                'shop_id' : '{$shop['id']}'
                , 'uid'   : '{$uuid}'
                , 'name'  : '游客' + uid
                , 'avatar': '/upload/5.jpg'
            }
        };
        var res = {};
        res.mine = options.data;
        res.mine.code = options.data.uid;
        // 服务的客服标识
        var kf_code = '';
        var kf_name = '';
        var kf_avatar = '';
        var uuid = '{$uuid}';
        var kf;
    </script>
    <script>
        var chat_ops = {
            init: function () {
                layui.use(['layer','util']);
                var that = this;
                kf = new NbWebSocket(options);
                kf.onopen = (e) => {
                    $(".chat-footer .server_status .layui-badge").html("已连接");
                }
                kf.onmessage = (e) => {
                    if (e.data == 'pong') return; // 过滤心跳
                    chat.handlerMessage(JSON.parse(e.data));
                }
                kf.onclose = (e) => {
                    $(".chat-footer .server_status .layui-badge").removeClass("layui-bg-green");
                    $(".chat-footer .server_status .layui-badge").html("已关闭");
                }
               
                $("#closeBtn").click(function () {
                    top.postMessage("hide_chat", '*');
                });

                // 发送
                $(".chat-container #sendBtn").click(function () {
                    if ($(".chat-container #sendBtn").hasClass('active')) {
                        that.sendMessage('');
                    }
                });
            },
            sendMessage: function (inMsg) {
                var that = this;
                if ('' == inMsg) {
                    var input = $("#textarea").val();
                } else {
                    var input = inMsg;
                }

                chat_box_ops.showGuestMessage(input);

                $("#textarea").val('');
                res.to.content = input;
                console.log(JSON.stringify({
                    type: 'chatMessage',
                    data: res
                }));
                kf.send(JSON.stringify({
                    type: 'chatMessage',
                    data: res
                }));

                $(".chat-container #sendBtn").removeClass('active');
            },
            sendCloseMessage: function (msg) {
                var that = this;
  
                stkf_ws_service.socketSend({
                    cmd: 'guest_close',
                    data: {
                        f_name: guest_name,
                        f_avatar: guest_avatar,
                        f_code: that.config_params['uuid'],
                        f_source: 'guest',
                        to_code: kf_code,
                        to_name: kf_name,
                        to_avatar: kf_avatar,
                        content: "对您的服务评价：" + msg
                    }
                });
                $("#closeBtn").click();
            }
        }
        

        var chat = {
            handlerMessage: function (data) {
                var that = this;
                switch (data['message_type']) {
                    // 已经被分配了客服
                    case 'kf_link':
                        res.to={
                            'code'    : data.data.code
                            ,'name'   : data.data.name
                            ,'avatar' : data.data.avatar
                            ,'shop_id': shop_id
                            ,'source' : 'guest'
                        }
                        
                        chat_box_ops.showSystemMessage(res.to.name + "非常高兴为您服务");
                        break;
                    case 'rep_in':
                        guest_name = options.data.name;
                        //到时候根据商家设置是否要强制打开
                        if (1 == that.config_params['auto_open']) {
                            top.postMessage("open_chat", '*');
                        }
                        break;
                    // 没有客服在线
                    case 'no_kf':
                        chat_box_ops.showKFMessage(data.data);
                        break;
                    case "system":
                        chat_box_ops.showKFMessage(data.data);
                        break;
                    // 客服全忙
                    case 'kf_busy':
                        chat_box_ops.showSystemMessage(data.data);
                        break;
                    case 'kf_close_guest'://客服主动关闭服务窗口
                        chat_box_ops.showKFMessage(data.data);
                        var cIndex = layer.confirm('是否满意本次服务 ？', {
                            title: '服务质量',
                            icon: '6',
                            btn: ['满意', '不满意'],
                            closeBtn: 0
                        }, function () {
                            that.sendCloseMessage("满意");
                            layer.close(cIndex);
                        }, function () {
                            that.sendCloseMessage("不满意");
                            layer.close(cIndex);
                        });
                        break;
                    // 聊天数据
                    case 'chatMessage':
                        chat_box_ops.showKFMessage(data.data.to);
                        break;
                    // 系统异常
                    case 'error':
                        chat_box_ops.showSystemMessage(data.data.msg);
                        break;
                }
            }
        };
        var chat_box_ops = {
            showKFMessage: function (data) {
                var ele = $(".wrap_hide .kf_wrap").clone();
                ele.find(".chat-date").html(layui.util.toDateString(new Date().getTime(), "yyyy-MM-dd HH:mm:ss"));
                ele.find(".chat-avatars img").attr("src", data.hasOwnProperty('f_avatar') ? data['f_avatar'] : data.avatar);
                ele.find(".chat-message").html(data['content']);

                $(".chat-box").append(ele);
                $(".chat-box").append($(".wrap_hide .chat-sep").clone());
                this.wordBottom();
            },
            showGuestMessage: function (msg) {
                var ele = $(".wrap_hide .guest_wrap").clone();
                ele.find(".chat-date").html(layui.util.toDateString(new Date().getTime(), "yyyy-MM-dd HH:mm:ss"));
                ele.find(".chat-avatars img").attr("src", options.data.avatar);
                ele.find(".chat-message").html(msg);

                $(".chat-box").append(ele);
                $(".chat-box").append($(".wrap_hide .chat-sep").clone());
                this.wordBottom();
            },
            showSystemMessage: function (msg) {
                var ele = $(".wrap_hide .system_wrap").clone();
                ele.find(".chat-system").html(msg);
                $(".chat-box").append(ele);
            },
            // 滚动到最底端
            wordBottom: function () {
                var box = $(".chat-box");
                box.scrollTop(box[0].scrollHeight);
            },
        };
    </script>
    <script>
        $(document).ready(function () {
            $.extend(true,options, parent.options);
            chat_ops.init();
            // 发送

            // 输入监听
            $(".chat-container #textarea").keyup(function (event) {
                var len = $(this).val().length;
                if (len == 0) {
                    $(".chat-container #sendBtn").removeClass('active');
                } else if (len > 0 && !$("#sendBtn").hasClass('active')) {
                    $(".chat-container #sendBtn").addClass('active');
                }
            });

            //输入enter健也可以发送
            $(document).keydown(function (event) {
                if (event.keyCode == 13) {
                    $(".chat-container #sendBtn").click();
                    return false;
                }
            });

            //目标网址加载完JS会调用这个方法通过iframe.contentWindow.postMessage('{}', '*');
            window.addEventListener('message', function (event) {
                console.log(event.data)
                // var json_data = eval('(' + event.data + ')');
                // var tmp_data = {
                //     f_name: "访客",
                //     f_avatar: guest_avatar,
                //     f_code: chat_ops.config_params['uuid'],
                //     content: json_data['kf_referer'],
                //     domain: json_data['kf_url'],
                //     ua: json_data['ua']
                // };
                // if ('open_chat' == json_data['cmd']) {
                //     if (!ws_connect_flag) {
                //         tmp_data['f_name'] = guest_name;
                //         stkf_ws_service.socketSend({
                //             cmd: 'guest_connect',
                //             data: tmp_data
                //         });
                //         ws_connect_flag = true;
                //     }
                // } else if ("guest_in" == json_data['cmd']) {
                //     stkf_ws_service.socketSend({
                //         cmd: 'guest_in',
                //         data: tmp_data
                //     });
                // }
            }, false);
        });
    </script>
</body>

</html>